import { uploadPictureUsingPost } from '@/services/backend/fileController';
import { InboxOutlined } from '@ant-design/icons';
import { message, UploadFile, type UploadProps } from 'antd';
import React from 'react';
import ImgCrop from 'antd-img-crop';
import Dragger from 'antd/es/upload/Dragger';
interface Props {
  id?: string;
  params?: any;
  onChange?: (fileList: UploadFile[]) => void;
  value?: UploadFile[];
  onFinish?: () => void;
  description: string;
}

const PictureCropUploader: React.FC<Props> = (props) => {
  const { id, value, params, description, onChange, onFinish } = props;
  const [loading, setLoading] = React.useState(false);
  const uploadProps: UploadProps = {
    name: 'file',
    listType: 'text',
    multiple: false,
    maxCount: 1,
    fileList: value,
    disabled: loading,
    onChange: ({ fileList }) => {
      onChange?.(fileList);
    },
    customRequest: async (fileObj: any) => {
      console.log(params);
      setLoading(true);
      try {
        const res = await uploadPictureUsingPost(
          {
            id,
            ...params,
          },
          {},
          fileObj.file,
        );
        fileObj.onSuccess(res.data);
        message.success('上传成功');
      } catch (e) {
        message.error('上传失败');
        fileObj.onError(e);
      }
      setLoading(false);
      onFinish?.();
    },
  };
  return (
    <ImgCrop rotationSlider aspectSlider>
      <Dragger {...uploadProps}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或者拖拽上传</p>
        <p className="ant-upload-hint">{description}</p>
      </Dragger>
    </ImgCrop>
  );
};
export default PictureCropUploader;
